<script setup>
import { computed, ref, toRaw } from 'vue';
import { getCode,userAuthentication,login, menuPermissions } from '../../api';
import { ElMessage } from 'element-plus';
import {useRouter} from 'vue-router'
import { useStore } from 'vuex';

//表单数据
const loginForm = ref({
  userName: '',
  passWord: '',
  validCode: ''
})

//切换表单(0登录 1注册)
const formType = ref(0)
//点击切换登录和注册
const handleChange = () => {
  if (formType.value === 1) {
    formType.value = 0
  } else {
    formType.value = 1
  }
  loginForm.value = {
    userName:'',
    passWord:'',
    validCode:''
  }
}

//账号校验规则
const validateUser = (rule,value,callback) => {
  //不能为空
  if(value === ''){
    callback(new Error('请输入账号'))
  }else{
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    phoneReg.test(value) ? callback() : callback(new Error('手机号格式错误'))
  }
}
//密码校验规则
const validatePass = (rule,value,callback) => {
  //不能为空
  if(value === ''){
    callback(new Error('请输入密码'))
  }else{
    const reg = /^[a-zA-z0-9_-]{4,16}$/
    reg.test(value) ? callback() : callback(new Error('密码格式错误,需要4-16位字符，'))
  }
}
//表单校验
const rules = ref({
  userName:[{validator:validateUser,trigger:'blur'}],
  passWord:[{validator:validatePass,trigger:'blur'}]
})

//发送短信
const countDown = ref({
  validText: '获取验证码',
  time: 60
})
let flag = false
const countDownChange = () => {
  //如果已发送不处理
  if (flag) {
    return
  }
  //判断手机号是否正确
  const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if (!loginForm.value.userName || !phoneReg.test(loginForm.value.userName)) {
    return ElMessage({
      message: '请检查手机号是否正确',
      type: 'error'
    })
  }
  //倒计时
  const time = setInterval(() => {
    if (countDown.value.time <= 0) {
      countDown.value.time = 60
      countDown.value.validText = '获取验证码'
      flag = false
      clearInterval(time)
    } else {
      countDown.value.time -= 1
      countDown.value.validText = `剩余${countDown.value.time}秒`
    }
  }, 1000)
  flag = true
  getCode({tel:loginForm.value.userName}).then(res => {
    console.log(res)
    if(res.data.code === 10000){
      ElMessage.success('发送成功')
    }else(
      ElMessage.error('发送失败')
    )
  })
}
const router = useRouter()
const loginFormRef = ref()
const store = useStore()

const routerList = computed(() => {
  return store.state.menu.routerList
})
//表单提交
const submitForm = async (fromEl) => {
  if(!fromEl){
    return
  }
  //手动触发校验
  await fromEl.validate((valid,fields) => {
    if(valid) {
      console.log('submit!')
      //注册页面
      if(formType.value === 1){
        userAuthentication(loginForm.value).then(res => {
          console.log(res)
          if(res.data.code===10000){
            ElMessage.success('注册成功，请登录')
            formType.value = 0
          }
        })
      }else{
        //登录页面
        login(loginForm.value).then(res => {
          if(res.data.code===10000){
            ElMessage.success('登录成功')
            //将token和用户信息缓存到浏览器
            localStorage.setItem('pz_token',res.data.data.token)
            localStorage.setItem('pz_userInfo',JSON.stringify(res.data.data.userInfo))
            menuPermissions().then(res => {
              store.commit('dynamicMenu',res.data.data)
              console.log(routerList)
              toRaw(routerList.value).forEach(item => {
                router.addRoute('main',item)
              })
              router.push('/')
            })
          }
        })
      }
    }else{
      console.log('error submit',fields)
    }
  })
}
</script>

<template>
  <el-row class="login-container" justify="center" :align="'middle'">
    <el-card style="max-width: 480px;">
      <template #header>
        <div class="card-header">
          <img src="../../../public/login-head.png" alt="">
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChange">{{ formType === 1 ? '返回登录' : '注册账号' }}</el-link>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" style="max-width: 600px" class="demo-ruleForm" :rules="rules">
        <el-form-item prop="userName">
          <el-input v-model="loginForm.userName" placeholder="手机号" :prefix-icon="UserFilled"></el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input v-model="loginForm.passWord" type="password" placeholder="密码" :prefix-icon="Lock"></el-input>
        </el-form-item>
        <el-form-item v-if="formType === 1" prop="validCode">
          <el-input v-model="loginForm.validCode" placeholder="验证码" :prefix-icon="Lock">
            <template #append>
              <span @click="countDownChange">{{ countDown.validText }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :style="{width:'100%'}" @click="submitForm(loginFormRef)">
            {{ formType === 1 ? '注册账号' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<style scoped lang="less">
:deep(.el-card__header) {
  padding: 0
}

.login-container {
  height: 100%;

  .card-header {
    background-color: #899fe1;

    img {
      width: 430px;
    }
  }

  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>